Full Text Search
✒️ 2025-07-16 20:34 내용 수정
프로젝트 진행 중 메모 목적으로 간단하게 정리했다. 나중에 이 부분은 더 공부한 뒤 정리할 예정이다.
참고 문서 : Valeri Karpov's Full Text Search using tsvector with Neon PostgreSQL, PostgreSQL Full Text Search, Lukas Fittl's Understanding Postres GIN Indexes: The Good and the Bad
tsvector
to_tsvector(config, text);
to_tsvector('english', 'apple');
- parsing to query
to_tsquery(config, text);
websearch_to_tsquery
websearch_to_tsquery(config, text);
검색 테스트
1. 테이블 생성
CREATE TABLE items (
id serial PRIMARY KEY,
title text,
description text
);
-- tsvector 컬럼 생성 (빌드 시 자동 생성)
ALTER TABLE items
ADD COLUMN search_vector tsvector GENERATED ALWAYS AS (
to_tsvector(
'english',
coalesce(title, '') || ' ' || coalesce(description, '')
)
) STORED;
2. GIN Index 생성
CREATE INDEX idx_items_search_vector ON items USING GIN(search_vector);
3. 검색 및 랭킹 정렬
SELECT *
FROM items
WHERE search_vector @@ websearch_to_tsquery('english', 'apple banana');
SELECT
id,
title,
ts_rank(search_vector, qry) AS rank
FROM items,
websearch_to_tsquery('english', 'apple banana') AS qry
WHERE search_vector @@ qry
ORDER BY rank DESC
LIMIT 20;